﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SimpleIR;
using System.Diagnostics.Contracts;

namespace RgnAnalyzer.Domain
{
	/// <summary>
	/// Represents reference from an unknown external location.
	/// </summary>
	internal sealed class AExternalRef : IComparable<AExternalRef>
	{
		/// <summary>
		/// The unique id associated with the external name ref.
		/// </summary>
		internal readonly int IDTAG;

		/// <summary>
		/// If this external ref is from a single static location then this is the name of that location.
		/// </summary>
		internal readonly IRStaticField StaticRef;

		internal AExternalRef(int idtag, IRStaticField staticloc)
		{
			this.IDTAG = idtag;
			this.StaticRef = staticloc;
		}

		internal static AExternalRef ComputeSummaryAExternalRef(List<AExternalRef> orefs)
		{
			bool oksfld = true;
			IRStaticField sfld = null;
			for(int j = 0; j < orefs.Count; ++j)
			{
				AExternalRef teref = orefs[j];
			
				if(teref.StaticRef != null)
				{
					if((oksfld) & ((sfld == null) | (sfld == teref.StaticRef)))
						sfld = teref.StaticRef;
					else
					{
						sfld = null;
						oksfld = false;
					}
				}
			}

			return new AExternalRef(GlobalAnalysisState.TProg.NameTable.ExternalRefCtrGen.GenNextVal(), sfld);
		}

		public override string ToString()
		{
 			return "$ext_" + (this.StaticRef != null ? (this.StaticRef.ToString() + "_") : "") + this.IDTAG; 
		}

		public int CompareTo(AExternalRef other)
		{ return this.IDTAG - other.IDTAG; }
	}
}
